package base.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import base.application.BaseApplication;

public class FileUtil {

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	public static int getExifOrientation(String filename) {
		if (TextUtils.isEmpty(filename))
			return -1;
		try {
			ExifInterface exif = new ExifInterface(filename);
			// if(Logger.isLoggingEnabled())Logger.info(ExifInterface.TAG_DATETIME,
			// ""+exif.getAttribute(ExifInterface.TAG_DATETIME));
			// if(Logger.isLoggingEnabled())Logger.info(ExifInterface.TAG_GPS_LATITUDE,
			// ""+exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
			// if(Logger.isLoggingEnabled())Logger.info(ExifInterface.TAG_GPS_LATITUDE_REF,
			// ""+exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF));
			// if(Logger.isLoggingEnabled())Logger.info(ExifInterface.TAG_GPS_LONGITUDE,
			// ""+exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
			// if(Logger.isLoggingEnabled())Logger.info(ExifInterface.TAG_GPS_LONGITUDE_REF,
			// ""+exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF));
			return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return -1;
	}

	// Constants used for the Orientation Exif TAG.
	public static Matrix getExifInterfaceMatrix(String filename) {
		if (TextUtils.isEmpty(filename))
			return null;
		Matrix matrix = new Matrix();
		int orientation = getExifOrientation(filename);
		switch (orientation) {
		case ExifInterface.ORIENTATION_UNDEFINED:
		case ExifInterface.ORIENTATION_NORMAL:
			break;
		case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:// left right reversed
														// mirror
			matrix.setScale(-1, 1);
			return matrix;
		case ExifInterface.ORIENTATION_ROTATE_180:
			matrix.setRotate(180);
			return matrix;
		case ExifInterface.ORIENTATION_FLIP_VERTICAL:// upside down mirror
			matrix.setScale(1, -1);
			return matrix;
		case ExifInterface.ORIENTATION_TRANSPOSE:// flipped about top-left <-->
													// bottom-right axis

			break;
		case ExifInterface.ORIENTATION_ROTATE_90:// rotate 90 cw to right it
			matrix.setRotate(90);
			return matrix;
		case ExifInterface.ORIENTATION_TRANSVERSE:// flipped about top-right
													// <--> bottom-left axis

			break;
		case ExifInterface.ORIENTATION_ROTATE_270:// rotate 270 to right it
			matrix.setRotate(270);
			return matrix;
		default:
			break;
		}
		return null;
	}

	public static Matrix getExifInterfaceMatrix(String filename, float scale) {
		if (TextUtils.isEmpty(filename))
			return null;
		Matrix matrix = new Matrix();
		int orientation = getExifOrientation(filename);
		switch (orientation) {
		case ExifInterface.ORIENTATION_UNDEFINED:
		case ExifInterface.ORIENTATION_NORMAL:
			break;
		case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:// left right reversed
														// mirror
			matrix.setScale(-scale, scale);
			return matrix;
		case ExifInterface.ORIENTATION_ROTATE_180:
			matrix.setRotate(180);
			break;
		case ExifInterface.ORIENTATION_FLIP_VERTICAL:// upside down mirror
			matrix.setScale(scale, -scale);
			return matrix;
		case ExifInterface.ORIENTATION_TRANSPOSE:// flipped about top-left <-->
													// bottom-right axis

			break;
		case ExifInterface.ORIENTATION_ROTATE_90:// rotate 90 cw to right it
			matrix.setRotate(90);
			break;
		case ExifInterface.ORIENTATION_TRANSVERSE:// flipped about top-right
													// <--> bottom-left axis

			break;
		case ExifInterface.ORIENTATION_ROTATE_270:// rotate 270 to right it
			matrix.setRotate(270);
			break;
		default:
			break;
		}
		matrix.setScale(scale, scale);
		return matrix;
	}

	@SuppressLint("NewApi")
	public static final String getPathFromUri(Context context, Uri uri) {
		if (context != null && uri != null) {
			if ("file".equals(uri.getScheme())) {
				return uri.getPath();
			}
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
				if (DocumentsContract.isDocumentUri(context, uri)) {
					// ExternalStorageProvider
					if (isExternalStorageDocument(uri)) {
						final String docId = DocumentsContract.getDocumentId(uri);
						final String[] split = docId.split(":");
						final String type = split[0];

						if ("primary".equalsIgnoreCase(type)) {
							return Environment.getExternalStorageDirectory() + "/" + split[1];
						}

						// TODO handle non-primary volumes
					}
					// DownloadsProvider
					else if (isDownloadsDocument(uri)) {

						final String id = DocumentsContract.getDocumentId(uri);
						final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

						return getDataColumn(context, contentUri, null, null);
					}
					// MediaProvider
					else if (isMediaDocument(uri)) {
						final String docId = DocumentsContract.getDocumentId(uri);
						final String[] split = docId.split(":");
						final String type = split[0];

						Uri contentUri = null;
						if ("image".equals(type)) {
							contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
						} else if ("video".equals(type)) {
							contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
						} else if ("audio".equals(type)) {
							contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
						}

						final String selection = "_id=?";
						final String[] selectionArgs = new String[] {
							split[1]
						};

						return getDataColumn(context, contentUri, selection, selectionArgs);
					}
				}
			}
			Cursor cursor = null;
			try {
				cursor = context.getContentResolver().query(uri, new String[] {
					MediaStore.Images.Media.DATA
				}, null, null, null);

				cursor.moveToFirst();
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				String fileName = null;
				if (column_index < cursor.getCount())
					fileName = cursor.getString(column_index);
				if (fileName == null) {
					fileName = getPathFromUri44(context, uri);
				}
				return fileName;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (cursor != null)
						cursor.close();
				} catch (Exception e) {
				}
			}

		}
		return null;
	}

	private static final String getPathFromUri44(Context context, Uri uri) {
		if (android.os.Build.VERSION.SDK_INT < 19) {
			return null;
		}
		Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);

		if (cursor != null) {
			try {
				cursor.moveToFirst();
				// document_id==video:38911
				final String document_id = "document_id";// 4.4以后版本document_id
				int column_index = cursor.getColumnIndexOrThrow(document_id);
				String document_id_value = cursor.getString(column_index);
				return getPathFromUri44(context, document_id_value);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (cursor != null)
						cursor.close();
				} catch (Exception e) {
				}
			}
		}

		return null;
	}

	private static final String getPathFromUri44(Context context, String wholeID) {
		if (TextUtils.isEmpty(wholeID)) {
			return null;
		}
		// String wholeID = "video:38911";
		// 获得资源唯一ID
		String id = wholeID.split(":")[1];
		// 定义索引字段
		String[] column = {
			MediaStore.Images.Media.DATA
		};

		//
		String sel = MediaStore.Images.Media._ID + "=?";

		Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, column, sel, new String[] {
			id
		}, null);

		int columnIndex = cursor.getColumnIndex(column[0]);
		String filePath = null;
		if (cursor != null) {
			try {
				if (cursor.moveToFirst()) {
					// DATA字段就是本地资源的全路径
					filePath = cursor.getString(columnIndex);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (cursor != null)
						cursor.close();
				} catch (Exception e) {
				}
			}
		}
		return filePath;
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for MediaStore Uris, and other file-based ContentProviders.
	 * 
	 * @param context
	 *            The context.
	 * @param uri
	 *            The Uri to query.
	 * @param selection
	 *            (Optional) Filter used in the query.
	 * @param selectionArgs
	 *            (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = {
			column
		};

		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	private static final int MAX_IMAGE_SIZE = 1024;

	public static Bitmap getBitmapFromUri(Uri uri, int maxSize) {
		if (maxSize <= 0) {
			maxSize = MAX_IMAGE_SIZE;
		}
		if (uri != null) {
			InputStream in = null;
			try {
				in = BaseApplication.getInstance().getApplicationContext().getContentResolver().openInputStream(uri);
				// Decode image size
				BitmapFactory.Options o = new BitmapFactory.Options();
				o.inJustDecodeBounds = true;
				BitmapFactory.decodeStream(in, null, o);
				in.close();
				return getBitmap(uri, maxSize, o.outWidth, o.outHeight);
			} catch (FileNotFoundException e) {
			} catch (IOException e) {
			}
		}
		return null;
	}

	// 2048 1024, 512
	private static Bitmap getBitmap(Uri uri, int maxSize, int outWidth, int outHeight) {
		Context context = BaseApplication.getInstance().getApplicationContext();
		InputStream in = null;
		try {
			int scale = 1;
			if (outHeight > maxSize || outWidth > maxSize) {
				scale = (int) Math.pow(2, (int) Math.round(Math.log(maxSize / (double) Math.max(outHeight, outWidth)) / Math.log(0.5)));
			}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			in = context.getContentResolver().openInputStream(uri);
			Bitmap b = BitmapFactory.decodeStream(in, null, o2);

			String filepath = FileUtil.getPathFromUri(context, uri);
			Matrix m = FileUtil.getExifInterfaceMatrix(filepath);
			if (m != null) {
				Bitmap bitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
				if (!b.equals(bitmap)) {
					b.recycle();
				}
				b = null;
				return bitmap;
			}
			return b;
		} catch (FileNotFoundException e) {
		} catch (Exception e) {
		} catch (OutOfMemoryError e) {
			if (in != null)
				try {
					in.close();
				} catch (IOException e1) {
				}
			in = null;
			return getBitmap(uri, maxSize / 2, outWidth, outHeight);
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e1) {
				}
			in = null;
		}

		return null;
	}

}
